import json
from neo4j import GraphDatabase

uri = "bolt://localhost:7687"
username = "neo4j"
password = "12345678"  # 改成你的密码

driver = GraphDatabase.driver(uri, auth=(username, password))

def import_apoc_json(json_file):
    nodes = []
    relationships = []

    print("🔍 解析 APOC 导出的 JSON 文件...")
    with open(json_file, 'r', encoding='utf-8') as f:
        for line_num, line in enumerate(f, 1):
            line = line.strip()
            if not line:
                continue
            try:
                data = json.loads(line)

                # 区分节点和关系
                if data.get("type") == "node":
                    nodes.append({
                        "id": data["id"],
                        "labels": data["labels"],
                        "properties": data["properties"]
                    })
                elif data.get("type") == "relationship":
                    relationships.append({
                        "id": data["id"],
                        "type": data["label"],  # 注意是 "label" 不是 "type"
                        "startNodeId": data["start"]["id"],
                        "endNodeId": data["end"]["id"],
                        "properties": data.get("properties", {})
                    })

            except json.JSONDecodeError as e:
                print(f"❌ 第 {line_num} 行 JSON 解析失败: {e}")
            except KeyError as e:
                print(f"❌ 第 {line_num} 行缺少字段: {e}")

    print(f"✅ 加载了 {len(nodes)} 个节点，{len(relationships)} 个关系")

    # 导入节点
    with driver.session() as session:
        for node in nodes:
            labels = ":".join(node["labels"])
            session.run(
                f"MERGE (n:{labels} {{id: $id}}) SET n += $props",
                id=node["id"],
                props=node["properties"]
            )

    # 导入关系
    with driver.session() as session:
        for rel in relationships:
            session.run(
                """
                MATCH (a {id: $start_id})
                MATCH (b {id: $end_id})
                MERGE (a)-[r:%s]->(b)
                SET r += $props
                """ % rel["type"],
                start_id=rel["startNodeId"],
                end_id=rel["endNodeId"],
                props=rel["properties"]
            )

    print("🎉 导入完成！")

# 调用
import_apoc_json("all-data.json")

# 关闭连接
driver.close()